const router = require('koa-router')()
const mongoose = require('mongoose')

const Image = mongoose.model('Image')
const Comment = mongoose.model('Comment')

router.post('/', async ctx => {
    await Image.findById(ctx.params.imageid)
    .then(doc => Comment.create(
        //node8.8+ {...ctx.request.body, image: ctx.params.imageid}
        Object.assign({},ctx.request.body,{image: ctx.params.imageid,imgfullname:doc.filename})
    ))
    .then(doc => ctx.body = doc)
    .catch(err => ctx.throw(500, err))
})

router.get('/',async ctx =>{
    await Comment.find({image : ctx.params.imageid}).sort({timestamp : -1})
    .then(doc => ctx.body = doc)
    .catch(err => ctx.throw(500, err))
})

module.exports = router
